package com.seednia.module.core.reference.ui.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.seednia.foundation.framework.dto.QueryParams;
import com.seednia.foundation.framework.service.AbstractWebRequestController;
import com.seednia.foundation.framework.service.RequestContext;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.foundation.framework.service.ServiceException;
import com.seednia.module.core.reference.dto.ReferenceCriteria;
import com.seednia.module.core.reference.dto.ReferenceDto;
import com.seednia.module.core.reference.service.IReferenceService;
import com.seednia.module.core.reference.service.impl.ReferenceDefaultService;

@Controller
public class ReferenceController extends AbstractWebRequestController {
	
	private IReferenceService service = null;
	
	public ReferenceController() 
	{
	}
	
	@RequestMapping(value="/list.html", method = RequestMethod.GET)
    public ModelAndView list(HttpServletRequest request) {
		
		List<ReferenceDto> result = null;
		try {
			RequestContext requestContext = super.createRequestContext(request);
			result = getService().getReferenceList(requestContext, null, new QueryParams(0, Integer.MAX_VALUE));
		} catch (ServiceException e) {
			e.printStackTrace();
		}

		Map<String, Object> model = new HashMap<String, Object>();
		
		model.put("list", result);
		
        return new ModelAndView("list", "model", model);
    }
	
	@RequestMapping(value="/details.html/{sid}", method = RequestMethod.GET)
    public ModelAndView details(@PathVariable("sid") Long sid, HttpServletRequest request) 
	{
		ReferenceDto result = null;
		if (sid != null) {
			ReferenceCriteria criteria = new ReferenceCriteria();
			criteria.setSid(sid);
			try {
				RequestContext requestContext = super.createRequestContext(request);
				result = getService().getReference(requestContext, criteria);
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}

		Map<String, Object> model = new HashMap<String, Object>();
		
		model.put("record", result);
		
        return new ModelAndView("details", "model", model);
    }
	

	public IReferenceService getService() {
		if (service == null) {
			//ServiceContainer.getInstance().getById(Iservice.class.getName());
			service = (IReferenceService)ServiceContainer.getInstance().getByType(ReferenceDefaultService.class);
		}
		return service;
	}

	public void setservice(IReferenceService service) {
		this.service = service;
	}

}
